/*
 * @Date         : 2024-05-12 15:03:37 星期0
 * @Author       : xut
 * @Description  :
 */
import grpc from "@grpc/grpc-js"
import helloStreamProto from "./helloworldstream.proto.js"

const MultiGreeterServiceImpl = {
  sayHelloStreamReply: (call) => {
    const { name, num_greetings } = call.request

    if (name === "") {
      call.emit("error", {
        code: grpc.status.INVALID_ARGUMENT,
        details: "request missing required field: name end",
      })
      // 'error' 事件表示发生错误并且流已关闭。所以可以省略 end 调用
      // call.end()
      return
    }

    if (Number.isNaN(num_greetings * 1)) {
      call.emit("error", {
        code: grpc.status.INVALID_ARGUMENT,
        details: `num_greetings is incorrect. expected number, got ${num_greetings}`,
      })
      // call.end()
      return
    }

    for (let i = 0; i < num_greetings; i++) {
      call.write({ message: `Greeting ${i + 1}, echo: Hello ${name}` })
    }
    call.end()
  },
}

function main() {
  const server = new grpc.Server()
  server.addService(
    helloStreamProto.MultiGreeter.service,
    MultiGreeterServiceImpl
  )
  server.bindAsync(
    "localhost:50051",
    grpc.ServerCredentials.createInsecure(),
    (err, port) => {
      if (err !== null) {
        return console.error(err)
      }

      console.log("gRPC listening on localhost:" + port)
    }
  )
}
main()
